package com.imooc.controller;


import com.google.gson.Gson;
import com.imooc.base.BaseInfoProperties;
import com.imooc.grace.result.GraceJSONResult;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.api.intercept.JWTCurrentUserInterceptor;
import com.imooc.pojo.Admin;
import com.imooc.pojo.BO.AdminBO;
import com.imooc.pojo.VO.AdminVO;
import com.imooc.service.AdminService;

import com.imooc.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * app端一键注册登录
 */
@RestController
@RequestMapping("admin")
@Slf4j
public class AdminController extends BaseInfoProperties {

    @Autowired
    private AdminService adminService;

    @Autowired
    private JWTUtils jwtUtils;

    @PostMapping("login")
    public GraceJSONResult login(@Valid @RequestBody AdminBO adminBO) {

        boolean isExist = adminService.adminLogin(adminBO);

        if (!isExist)
            return GraceJSONResult.errorCustom(
                    ResponseStatusEnum.ADMIN_LOGIN_ERROR);

        Admin admin = adminService.getAdminInfo(adminBO);
        AdminVO adminVO = new AdminVO();

        BeanUtils.copyProperties(admin, adminVO);

        String adminToken = jwtUtils.createToken(new Gson().toJson(adminVO), TOKEN_ADMIN_PREFIX);

        return GraceJSONResult.ok(adminToken);
    }


    @GetMapping("info")
    public GraceJSONResult info() {
        Admin admin = JWTCurrentUserInterceptor.adminUser.get();

        AdminVO adminVO = new AdminVO();
        BeanUtils.copyProperties(admin, adminVO);

        return GraceJSONResult.ok(adminVO);
    }


    @PostMapping("logout")
    public GraceJSONResult logout() {
        return GraceJSONResult.ok();
    }
}
